var path = require('path');

var gulp = require('gulp');
var rename = require('gulp-rename');
var less = require('gulp-less');
var minifyCSS = require('gulp-minify-css');
var rename = require('gulp-rename');
var seajs = require("gulp-seajs");
var concat = require("gulp-concat");
var clean = require("gulp-clean");
var uglify = require("gulp-uglify");

var scripts =['./js/intro.js', './js/tesla-properties.js', './js/tesla-api.js', 
              './js/tesla-ajax.js', './js/tesla-msg.js', './js/tesla-util.js',
              './js/config-handler.js', './js/action-handler.js', './js/event-listener.js', 
              './js/common.js', './js/outro.js'];

gulp.task('buildLess', function() {
	return gulp.src(['./less/tesla-mobile-ui.all.less'])
        // .pipe(watch())
        .pipe(less({
            paths: [path.join(__dirname, 'less'), path.join(__dirname, 'widget/*/src')]
        }))
        .pipe(gulp.dest('./cmbc/css'))
        .pipe(minifyCSS())
        .pipe(rename({
            suffix: '.min',
            extname: ".css"
        }))
        .pipe(gulp.dest('./cmbc/css'));
});

gulp.task('init', function () {
	return gulp.src('./cmbc/js/tesla-*.js', {read: false})
    		.pipe(clean());
});

gulp.task('concatjs', function () {
	return gulp.src(scripts)
		.pipe(concat('tesla-mobile.js'))
		.pipe(gulp.dest('./js/'))
		.pipe(seajs('tesla-mobile'))
		.pipe(gulp.dest('./cmbc/js'))
		.pipe(uglify())
		.pipe(rename({
			suffix: '.min',
            extname: ".js"
		}))
		.pipe(gulp.dest('./cmbc/js'));
});

gulp.task('seajsBuild', function(){
	return gulp.src('./js/tesla-mobile.js')
	    .pipe(seajs('main'))
	    .pipe(gulp.dest('./dist'));
});

gulp.task('minifyJS', function () {
	gulp.src('./dist/*.js')
    	.pipe(uglify())
    	.pipe(rename({
            suffix: '.min',
            extname: ".js"
        }))
    	.pipe(gulp.dest('./dist'));
});

/*
gulp.task('bower', function () {
	return bower().pipe(gulp.dest('./lib/'))
});

gulp.task('test', function() {
	// Be sure to return the stream
	  return gulp.src(['./src/*.js'])
	    .pipe(karma({
	    	configFile: 'karma.conf.js',
	    	action: 'run'
	    }))
	    .on('error', function(err) {
	    	// Make sure failed tests cause gulp to exit non-zero
	    	throw err;
	    });
});

gulp.task('checkJs', function(){
	return gulp.src(['./src/*.js'])

    // pass your directives
    // as an object
    .pipe(jslint({
    }))

    // error handling:
    // to handle on error, simply
    // bind yourself to the error event
    // of the stream, and use the only
    // argument as the error object
    // (error instanceof Error)
    .on('error', function (error) {
        console.error(String(error));
    });
});
*/

//gulp.task('default', ['buildLess', 'bower', 'seajsBuild']);
gulp.task('default', ['buildLess', 'init', 'concatjs']);
